package com.weiyuwqj.admin.controller.admin.log.aop;

import com.weiyuwqj.admin.controller.admin.log.annotation.LogAnnotation;
import com.weiyuwqj.api.model.SysLogCollect;
import com.weiyuwqj.api.service.SysLogCollectService;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.JsonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * 自定义切面，和自定义注解联合使用完成日志收集
 * @author Administrator
 *
 */
@Component
@Aspect
public class LogAop {

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private SysLogCollectService sysLogCollectService;
	
	@Pointcut(value="@annotation(com.weiyuwqj.admin.controller.admin.log.annotation.LogAnnotation)")
	public void pointCut(){
		
	}
	
	@Around(value="pointCut()&&@annotation(logAnnotation)")
	public Object aroundAdvice(ProceedingJoinPoint pjp, LogAnnotation logAnnotation) throws Throwable{
		// 获取模块，查询日志时定位
		String module = logAnnotation.module();
		// 获取描述，定位相应模块下的具体某个方法，并了解方法具体用途
		String desc = logAnnotation.description();


		//创建日志收集类
		SysLogCollect collectLog = new SysLogCollect();
		
		// 获取数据并赋值给日志类，存储于数据库
		//获取模块名并赋值
		collectLog.setModule(module);
		// 获取描述内容并赋值
		collectLog.setDescription(desc);
		// 获取方法名并赋值
		MethodSignature methodSignature=(MethodSignature) pjp.getSignature();
		collectLog.setMethod(methodSignature.getName());
		// 获取参数并赋值
		collectLog.setArgs(JsonUtils.toJson(pjp.getArgs()));
		Integer userId = (Integer)request.getSession().getAttribute("userId");
		String userName = (String) request.getSession().getAttribute("username");
		String  ip = IpUtils.get();
		collectLog.setUserId(userId);
		collectLog.setUserName(userName);
		collectLog.setUserIp(ip);
		collectLog.setCreateTime(new Date());
		// 往数据库中添加数据
		sysLogCollectService.save(collectLog);
		return pjp.proceed() ;
		
	}
	
	
}
